package cn.jbooter.restweb.autoconfigure.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.jbooter.coms.constants.IBaseConstants;
import cn.jbooter.coms.utils.CaptchaUtil;

/**
 * 验证码
 * @author hejian
 *
 */
@Controller
@RequestMapping(value="/frame")
public class CaptchaController {

	private static final String CACHE_PRAGMA_KEY = "Pragma";
	private static final String CACHE_PRAGMA_VALUE = "no-cache";
	private static final String CACHE_CONTROL_KEY = "Cache-Control";
	private static final String CACHE_CONTROL_VALUE = "no-cache";
	private static final String CACHE_EXPIRES_KEY = "Expires";
	private static final Integer CACHE_EXPIRES_VALUE = -10;
	
		
	/**
	 * 生成图片验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/captcha",method=RequestMethod.GET)
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存
        response.setHeader(CACHE_PRAGMA_KEY, CACHE_PRAGMA_VALUE);
        response.setHeader(CACHE_CONTROL_KEY, CACHE_CONTROL_VALUE);
        response.setDateHeader(CACHE_EXPIRES_KEY, CACHE_EXPIRES_VALUE);
        //生成验证码图片
        CaptchaUtil captcha = new CaptchaUtil(110,40,4,100);
        //向session中写入验证码
        HttpSession session = request.getSession();
        session.setAttribute(IBaseConstants.CAPTCHA_SESSION_KEY, captcha.getCode());
        captcha.write(response.getOutputStream());
	}
	
}
